package org.geekbang.thinking.in.spring.configuration.metadata;

import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * 外部化配置示例
 *
 * @author wangyh2
 * @version v1.0
 * @since 2021-10-21 20:39
 */
@PropertySource("classpath:/META-INF/user-bean-definitions.properties")
public class PropertySourceDemo {

    /**
     * user.name 是 Java Properties 默认存在，当前用户：weiyi，而非配置文件中定义"死神007"
     *
     * @param id
     * @param name
     * @return
     */
    @Bean
    public User user(@Value("${user.id}") Long id, @Value("${user.name}") String name) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        return user;
    }


    public static void main(String[] args) {

        // 1, 注册 applicationContext
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 2, 注册当前类作为 Configuration Class
        applicationContext.register(PropertySourceDemo.class);

        // 3, 注册新的PropertySource
        Map<String, Object> propertiesSource = new HashMap<>();
        propertiesSource.put("user.name", "sishen007");
        org.springframework.core.env.PropertySource<Map<String, Object>> propertySource = new MapPropertySource("first-property-source", propertiesSource);
        applicationContext.getEnvironment().getPropertySources().addFirst(propertySource);

        // 4, 启动 Spring 应用上下文
        applicationContext.refresh();
        // 5, beanName 和 bean 映射
        Map<String, User> userMap = applicationContext.getBeansOfType(User.class);
        for (Map.Entry<String, User> entry : userMap.entrySet()) {
            System.out.printf("User Bean name : %s , content : %s \n", entry.getKey(), entry.getValue());
        }

        // 6, 打印当前有多少个PropertySource
        System.out.println(applicationContext.getEnvironment().getPropertySources());
        // 7, 关闭 Spring 应用上下文
        applicationContext.close();
    }
}
